﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class LapBaoCaoCongNoThangBLL : BaseBLL
    {
        public class KhachHangOnGui
        {
            int _ID;
            float _NoDau;
            float _PhatSinh;

            public int ID
            {
                get { return _ID; }
                set { _ID = value; }
            }

            public float NoDau
            {
                get { return _NoDau; }
                set { _NoDau = value; }
            }
            
            public float PhatSinh
            {
                get { return _PhatSinh; }
                set { _PhatSinh = value; }
            }

            public KhachHangOnGui()
            {
                _ID = -1;
                _NoDau = 0;
                _PhatSinh = 0;
            }
        }

        DAL.KhachHangDAO _KhachHangDAO;
        DAL.BaoCaoNoThangDAO _BaoCaoNoDAO;

        public LapBaoCaoCongNoThangBLL()
        {
            _KhachHangDAO = new DAL.KhachHangDAO();
            _BaoCaoNoDAO = new DAL.BaoCaoNoThangDAO();
        }

        public int LapBaoCao(int Thang, List<KhachHangOnGui> khs)
        {
            try
            {
                System.Data.SqlClient.SqlConnection Connection = OpenConnection();
                System.Data.SqlClient.SqlTransaction Transaction = BeginTransaction();

                DTO.BaoCaoNoThangDTO baocaonoDto = new DTO.BaoCaoNoThangDTO();
                baocaonoDto.Thang = Thang;

                foreach (KhachHangOnGui k in khs)
                {
                    DTO.KhachHangDTO khDto = new DTO.KhachHangDTO();
                    khDto.ID = k.ID;
                    if (_KhachHangDAO.Select(Connection, Transaction, ref khDto) <= 0)
                    {
                        Rollback();
                        CloseConnection();
                        return 1;
                    }

                    baocaonoDto.IDKhachHang = k.ID;
                    baocaonoDto.NoDau = k.NoDau;
                    baocaonoDto.PhatSinh = k.PhatSinh;
                    baocaonoDto.NoCuoi = k.NoDau + k.PhatSinh;

                    _BaoCaoNoDAO.Insert(Connection, Transaction, baocaonoDto);
                }

                Commit();
                CloseConnection();
                return 0;
            }
            catch (System.Exception ex)
            {
                Rollback();
                CloseConnection();
                throw new System.Exception("LapBaoCao Failed " + ex.Message);
            }
            finally
            {
                CloseConnection();
            }
        }
    }
}
